/*
 * @(#) UserControl
 *
 * <br> Copyright:  Copyright (c) 2017
 * <br> @author caijinhuang
 * <br> 2017-12-18 16:01:12
 */

package com.sunsharing.sharemeeting.web.controll.usermanagement;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sunsharing.share.common.text.EncodeUtil;
import com.sunsharing.sharemeeting.service.api.UserService;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.sunsharing.sharemeeting.entity.ResponseModel;
import com.sunsharing.sharemeeting.entity.User;

/**
 * 用户管理
 */
@Controller
@RequestMapping("/user")
public class UserControl {
    @Resource
    UserService userService;

    /**
     * 修改密码
     * @param params = {
     *        oldPassword:旧密码
     *        newPassword:新密码
     * }
     * @return
     */
    @RequestMapping(value = "/changePassWd.do", method = RequestMethod.POST)
    @ResponseBody
    public String changePassWd(@RequestBody JSONObject params, HttpSession session) {
        ResponseModel responseModel = null;
        User user = (User) session.getAttribute("user");
        // System.out.println(EncodeUtil.md5(params.getString("oldPassword")));
        String oldPw = EncodeUtil.encodeBase64(EncodeUtil.md5(params.getString("oldPassword")).getBytes());
        String newPw = EncodeUtil.encodeBase64(EncodeUtil.md5(params.getString("newPassword")).getBytes());
        if (user != null && user.getPassword().equals(oldPw)) {
            if (userService.changePassWd(user.getUsername(), newPw) > 0) {
                responseModel = new ResponseModel(true, "修改成功", null);
                session.removeAttribute("user");//清除用户session
            }
        } else {
            responseModel = new ResponseModel(false, "原密码错误，请重试", null);
        }
        return JSON.toJSONString(responseModel);
    }

    /**
     * 密码重置
     * @param params = {
     *              userId:用户Id;
     * }
     * @return
     */
    @RequestMapping(value = "/passWordReset.do", method = RequestMethod.POST)
    @ResponseBody
    public String passWordReset(@RequestBody JSONObject params,HttpSession session)
        throws UnsupportedEncodingException, NoSuchAlgorithmException {
        ResponseModel responseModel = null;
        if (userService.changePassWd(params.getString("userId"),
            EncodeUtil.encodeBase64(EncodeUtil.md5("root").getBytes())) > 0) {
            responseModel = new ResponseModel(true, "重置成功，新密码为root", null);
            session.removeAttribute("user");//清除用户session
        } else {
            responseModel = new ResponseModel(false, "重置失败", null);
        }
        return JSON.toJSONString(responseModel);
    }


    /**
     * 用户角色权限修改
     * @param params = {
     *         roleId:'' 修改后的角色ID
     *         userIds:[] 待修改的用户id数组。
     * }
     * @return
     */
    @RequestMapping(value = "/changeUserRole.do", method = RequestMethod.POST)
    @ResponseBody
    public String changeUserRole(@RequestBody JSONObject params) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        JSONArray array = params.getJSONArray("userIds");
        List<String> userIdList = new ArrayList<String>();
        for (int i = 0; i < array.size(); i++) {
            userIdList.add(array.getString(i));
        }
        userService.updateUserRole(params.getString("roleId"), userIdList);
        ResponseModel responseModel = new ResponseModel(true, "修改成功", null);
        return JSON.toJSONString(responseModel);
    }

    /**
     * 用户注册
     * @param params = {
     *          username:账号
     *          password:密码
     *          nickname:姓名
     *          sex:性别
     *          department：部门
     *          email:邮箱
     *          phone:电话
     * }
     * @return
     */
    @RequestMapping(value = "/regist.do", method = RequestMethod.POST)
    @ResponseBody
    public String userRegist(@RequestBody JSONObject params,HttpSession session)
        throws UnsupportedEncodingException, NoSuchAlgorithmException {
        ResponseModel responseModel = null;
        User currentUser = (User) session.getAttribute("user");
        if (currentUser.getRoleName().equals("super_admin")) {
            User user = JSON.parseObject(params.toJSONString(),User.class);
            user.setPassword(EncodeUtil.encodeBase64(EncodeUtil.md5(user.getPassword()).getBytes()));
            userService.userRegist(user);
            responseModel = new ResponseModel(true, "注册成功", null);
        } else {
            responseModel = new ResponseModel(false, "权限不够，注册失败", null);
        }
        return JSON.toJSONString(responseModel);
    }

    /**
     * 验证账号是否可用
     * @param params = {
     *              username:用户账号
     * }
     * @return
     */
    @RequestMapping(value = "/isAvailable.do", method = RequestMethod.POST)
    @ResponseBody
    public String isAvailable(@RequestBody JSONObject params) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        ResponseModel responseModel = null;
        if (userService.checkUser(params.getString("username")) == null) {
            responseModel = new ResponseModel(true, "账号可用", null);
        } else {
            responseModel = new ResponseModel(false, "账号已经存在", null);
        }
        return JSON.toJSONString(responseModel);
    }

    /**
     * 用户信息检索：模糊查询
     * @param params = {
     *              username:用户账号
     * }
     * @return
     */
    @RequestMapping(value = "/searchUser.do", method = RequestMethod.POST)
    @ResponseBody
    public String searchUser(@RequestBody JSONObject params) {
        List<User> ulist = userService.searchUser(params.getString("username"));
        ResponseModel responseModel = new ResponseModel(true, "查询成功", ulist);
        return JSON.toJSONString(responseModel);
    }

    /**
     * 删除用户
     * @param params = {
     *              userId:用户Id
     * }
     * @return
     */
    @RequestMapping(value = "/deleteUser.do", method = RequestMethod.POST)
    @ResponseBody
    public String deleteUser(@RequestBody JSONObject params) {
        int result = userService.deleteUser(params.getString("userId"));
        ResponseModel responseModel = null;
        if (result > 0) {
            responseModel = new ResponseModel(true, "删除成功", null);
        } else {
            responseModel = new ResponseModel(false, "删除失败", null);
        }
        return JSON.toJSONString(responseModel);
    }


    /**
     * 上传注册用户信息表
     * @param file 上传的文件流
     * @return
     */
    @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
    @ResponseBody
    public String inputUsers(@RequestParam("file") MultipartFile file) throws IOException {
        ResponseModel responseModel = null;
        if (file != null) {
            String result = userService.registMoreUser(file.getInputStream());
            if (!result.equals("success")) {
                responseModel = new ResponseModel(false, "导入失败，由于："+result, null);
            } else {
                responseModel = new ResponseModel(true, "导入成功", null);
            }
        }
        return JSON.toJSONString(responseModel);
    }

}
